package com.example.woke;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bumptech.glide.Glide;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.GlideApp;
import com.woke.method.Intentnet;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import cn.jpush.android.api.JPushInterface;

public class ForgetpswActivity extends Activity implements OnClickListener {

    private EditText mEphone, mEokcode, mEnewp, mEdoubp,editimageCode;
    private TextView mTok;
    private TextView mTcode;
    //	private ProgressBar mBar;
    private int jtime = 60;
    private Runnable runnableRef = new Runnable() {
        public void run() {
            if (jtime == 0) {
                Message msg = new Message();
                msg.what = 911;
                mHandler.sendMessage(msg);
                mHandler.removeCallbacks(runnableRef);
            } else {
                jtime = jtime - 1;
                Message msg = new Message();
                msg.what = 109;
                mHandler.sendMessage(msg);
            }

            mHandler.postDelayed(runnableRef, 1000);
        }
    };

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 911) {
                mTcode.setText("点击发送验证码");
                mHandler.removeCallbacks(runnableRef);
                jtime = 60;
                mTcode.setClickable(true);
                mTcode.setBackgroundResource(R.drawable.rect_lightred);
            } else if (msg.what == 109) {
                mTcode.setText("(" + jtime + ")秒后重新发送");
                mTcode.setBackgroundResource(R.drawable.rect_lightgray);
                mTcode.setClickable(false);
            } else if (msg.what == 1) {
//				mBar.startAnimation(
//						AnimationUtils.loadAnimation(ForgetpswActivity.this, R.anim.btn_rotate));
//				mBar.setVisibility(View.VISIBLE);
            } else if (msg.what == 2) {
//				mBar.clearAnimation();
//				mBar.setVisibility(View.GONE);
            }
        }
    };
    private Intentnet net;
    private RelativeLayout mRelativ;

    ImageView imageCode;
    String registrationID;
    Dialog mydialog;
    private AlertView mAlertView;
    long lastClick = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpsw);
        registrationID = JPushInterface.getRegistrationID(ForgetpswActivity.this);

        net = new Intentnet();
        intview();
        imageYzm();
    }

    private void intview() {
        findViewById(R.id.avforget_image_back).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });

//		mBar = (ProgressBar) findViewById(R.id.avforget_progre_bar);
        mRelativ = (RelativeLayout) findViewById(R.id.avforget_psw_frame);
        mEphone = (EditText) findViewById(R.id.avforget_edit_phone);
        mEokcode = (EditText) findViewById(R.id.avforget_edit_code);
        mEnewp = (EditText) findViewById(R.id.avforget_edit_newpsw);
        mEdoubp = (EditText) findViewById(R.id.avforget_edit_doublepsw);
        editimageCode = (EditText) findViewById(R.id.forget_edit_img);

        mTcode = (TextView) findViewById(R.id.avforget_text_getcode);
        mTcode.setOnClickListener(this);

        mTok = (TextView) findViewById(R.id.avforget_text_ok);
        mTok.setOnClickListener(this);

        imageCode = (ImageView) findViewById(R.id.forget_image_code);
        imageCode.setOnClickListener(this);
    }

    private void getdatacode(String phone) {
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(ForgetpswActivity.this);
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "Public");
        params.put("a", "sendCode");
        params.put("username", phone);
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("response", "" + response);
                try {
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        Toast.makeText(ForgetpswActivity.this, "验证码已发送！", Toast.LENGTH_SHORT).show();
                        Thread thread = new Thread(runnableRef);
                        thread.start();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("response", "失败" + responseString);
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
//				Message msg = new Message();
//        		msg.what = 1;//��������
//        		mHandler.sendMessage(msg);
                mRelativ.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mTcode.setClickable(true);
                Log.e("response", "wwwww");
//				Message msg = new Message();
//        		msg.what = 2;//�رն���
//        		mHandler.sendMessage(msg);
                mRelativ.setVisibility(View.GONE);
//				Log.e("response", "���");
            }
        });
    }

    private void registerphone(final String number, String code, final String psw) {
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(ForgetpswActivity.this);
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "user");
        params.put("a", "forgetpw");
        params.put("username", number);
        params.put("code", code);
        params.put("password", psw);
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("response$$$", "" + response);
                try {
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        Toast.makeText(ForgetpswActivity.this, "新密码设置成功！", Toast.LENGTH_SHORT).show();
                        finish();
                    } else if (flag.equals("unknow")) {
                        String tooltip = response.getString("info");
                        if(response.has("data")){
                            JSONObject dataObj = response.getJSONObject("data");
                            if(dataObj!=null&&dataObj.has("data")){
                                tooltip = dataObj.getString("data");
                            }
                        }
                        Toast.makeText(ForgetpswActivity.this, "" + tooltip, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
//				Message msg = new Message();
//        		msg.what = 1;//��������
//        		mHandler.sendMessage(msg);
                mTok.setBackgroundDrawable(getResources().getDrawable(
                        R.drawable.rect_lightgray));
                mTok.setClickable(false);
                mRelativ.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("response", "ʧ��" + responseString);
                Toast.makeText(ForgetpswActivity.this, "新密码设置失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
//				Message msg = new Message();
//        		msg.what = 2;//�رն���
//        		mHandler.sendMessage(msg);
                mTok.setBackgroundDrawable(getResources().getDrawable(
                        R.drawable.rect_lightred));
                mTok.setClickable(true);
                mRelativ.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.avforget_text_ok:
                String number = mEphone.getText().toString().trim();
                String code = mEokcode.getText().toString().trim();
                String psw = mEnewp.getText().toString().trim();
                String psws = mEdoubp.getText().toString().trim();
                if (number.equals("") || null == number) {
                    Toast.makeText(ForgetpswActivity.this, "手机号码不能为空！", Toast.LENGTH_SHORT).show();
                } else if (net.isMobile(number) == false) {
                    Toast.makeText(ForgetpswActivity.this, "非法的手机号", Toast.LENGTH_SHORT).show();
                } else if (code.equals("") || null == code) {
                    Toast.makeText(ForgetpswActivity.this, "请输入手机验证码！", Toast.LENGTH_SHORT).show();
                } else if (psw.equals("") || null == psw || psws.equals("") || null == psws) {
                    Toast.makeText(ForgetpswActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
                } else if (!psw.equals(psws)) {
                    Toast.makeText(ForgetpswActivity.this, "两次输入密码不一样！", Toast.LENGTH_SHORT).show();
                } else {
                    registerphone(number, code, psw);
                }
                break;

            case R.id.avforget_text_getcode:
                String phone1 = mEphone.getText().toString().trim();
                String imageCode = editimageCode.getText().toString().trim();
                Intentnet intentnet = new Intentnet();
                if (phone1.equals("") || null == phone1) {
                    Toast.makeText(ForgetpswActivity.this, "手机号码不能为空！", Toast.LENGTH_SHORT).show();
                } else if (intentnet.isMobile(phone1) == false) {
                    Toast.makeText(ForgetpswActivity.this, "手机号码不正确！", Toast.LENGTH_SHORT).show();
                } else if(TextUtils.isEmpty(imageCode)){
                    Toast.makeText(ForgetpswActivity.this, "请输入图形验证码！", Toast.LENGTH_SHORT).show();
                }else {
//                    getdatacode(phone1);
                    if (!fastClick()){
                        mydialog=Util.createLoadingDialog(ForgetpswActivity.this);
                        yzm(phone1,imageCode);
                    }
//                    mTcode.setClickable(false);
                }
                break;
            case R.id.forget_image_code:
                if (!fastClick()){
                    imageYzm();
                }
                break;
            default:
                break;
        }
    }
    private void imageYzm() {
        registrationID=String.valueOf(System.currentTimeMillis());
        String url=Constant.IMAGEYZM+registrationID;
        Log.e("imageYzm",url);
        GlideApp.with(this)
                .load(url)
                .placeholder(R.mipmap.icn__launch_oem)
                .error(R.mipmap.icn__launch_oem)
                .into(imageCode);
    }
    //图形验证码后短信验证码
    private void yzm(String mobile,String imcode) {
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("mobile",mobile);
        params.put("code",imcode);
        params.put("token",registrationID);
        Log.e("图形验证码后短信验证码arams",params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.DXYZM, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Util.closeDialog(mydialog);
                //判断状态码
                if(i == 200){
                    //获取结果
                    try {
                        String result = new String(bytes, "utf-8");
                        //                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("图形验证码后短信验证码Result", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String flag = jsonObject.getString("flag");
                            if(flag.equals("success")){
                                Toast.makeText(ForgetpswActivity.this, "验证码已发送！", Toast.LENGTH_SHORT).show();
                                Thread thread = new Thread(runnableRef);
                                thread.start();
                            }else {
                                String tooltip = jsonObject.getString("info");
                                if(jsonObject.has("data")){
                                    JSONObject dataObj = jsonObject.getJSONObject("data");
                                    if(dataObj!=null&&dataObj.has("data")){
                                        tooltip = dataObj.getString("data");
                                    }
                                }
                                mAlertView=new AlertView("提示",tooltip, null, new String[]{"确定"}, null, ForgetpswActivity.this, AlertView.Style.Alert,null);
                                mAlertView.show();                            }
//
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(mydialog);
            }
        });
    }
    public boolean fastClick() {
        if (System.currentTimeMillis() - lastClick < 1000) {
            Toast.makeText(ForgetpswActivity.this,"不要点击过快！",Toast.LENGTH_SHORT).show();
            return true;
        }
        lastClick = System.currentTimeMillis();
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mAlertView != null && mAlertView.isShowing()) {
                mAlertView.dismiss();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);

    }
}
